package com.ljm.shirojwt.config;

import com.ljm.shirojwt.shiro.JwtFilter;
import com.ljm.shirojwt.shiro.TestRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(TestRealm testRealm){
        //需要注意这里是DefaultWebSecurityManager，该对象是专门用于整合springboot使用的SecurityManager，
        // 而不是使用DefaultSecurityManager
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(testRealm);

        return defaultWebSecurityManager;
    }

    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        //封装ShiroFilter的过滤器工厂
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        //配置路径与该路径使用的过滤器
        HashMap<String, String> filteDefinitionrMap = new HashMap<>();
        filteDefinitionrMap.put("/login","anon");//不用登陆验证就能访问
        filteDefinitionrMap.put("/**","jwt");//必须登录后才能访问

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filteDefinitionrMap);
        //除了使用shiro内置的服务器，还可以自定义过滤器，然后通过下面的方法添加进去。
        //shiroFilterFactoryBean.setFilters(map);
        return shiroFilterFactoryBean;
    }
}
